@SuppressWarnings({"all"})
class Producer implements Runnable {

    SynContainer container;

    public Producer(SynContainer c) {
        this.container = c;
    }

    @Override
    public void run() {
        for (int i = 0; i < 10; i++) {
            try {
                container.push(new Goods(i));
                if (i == 5) {
                    Thread.sleep(200);
                }
            } catch (InterruptedException e) {
                e.printStackTrace();

            }
        }
    }
}

@SuppressWarnings({"all"})
class Consumer implements Runnable {
    SynContainer container;

    public Consumer(SynContainer c) {
        this.container = c;
    }

    @Override
    public void run() {
        for (int i = 0; i < 100; i++) {
            try {
                Goods goods = container.pop();
                if (i == 5) {
                    Thread.sleep(200);
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}


@SuppressWarnings({"all"})
// 缓冲区
class SynContainer {
    // 缓存区大小，可存放10个
    Goods[] goods = new Goods[10];
    // 存放的产品数目,开始为0
    static int count = 0;

    // 存放产品
    public synchronized void push(Goods g) throws InterruptedException {
        // 如果缓冲区满了,则等待
        while (count == goods.length) {
            System.out.println("缓冲区已满，暂停生产");
            this.wait();
        }
        goods[count] = g;
        System.out.println("生产了第" + g.id + "个物品");
        count++;
        this.notify();
    }

    // 取出产品
    public synchronized Goods pop() throws InterruptedException {
        // 如果缓冲区为0,则等待
        while (count == 0) {
            System.out.println("缓冲区为0,暂停消费");
            this.wait();
        }
        count--;
        Goods g1 = goods[count];
        System.out.println("消费了第" + g1.id + "个物品");
        notifyAll();
        return g1;
    }
}

@SuppressWarnings({"all"})
class Goods {
    int id;

    public Goods(int id) {
        this.id = id;
    }
}

@SuppressWarnings({"all"})
public class ProducerConsumer {
    public static void main(String[] args) {
        SynContainer container = new SynContainer();
        Producer producer = new Producer(container);
        Consumer consumer = new Consumer(container);
        new Thread(producer).start();
        new Thread(consumer).start();
    }
}
